package com.chenjun.designpattern.behavior.iterator;

public class 迭代器模式
{
	public static void main(String[] args)
	{
		Teacher<String> teacher = new ConcreteTeacher();
		Iterator<String> iterator = teacher.createIterator();
		for ( ;  ! iterator.isDone(); iterator.next())
		{
			System.out.println(iterator.currentItem());
		}
	}
}

interface Teacher<T>
{
	public Iterator<T> createIterator();
}

interface Iterator<T>
{
	public void first();

	public void next();

	public boolean isDone();

	public T currentItem();
}

class ConcreteTeacher implements Teacher<String>
{
	private String[] present = { "张三", "李四", "王五" };

	@Override
	public Iterator<String> createIterator()
	{
		return new ConcreteIterator(this);
	}

	public String getElement(int index)
	{
		if ( index < present.length )
		{
			return present[index];
		}
		else
		{
			return null;
		}
	}

	public int getSize()
	{
		return present.length;
	}
}

class ConcreteIterator implements Iterator<String>
{
	private ConcreteTeacher concreteTeacher;
	private int index = 0;
	private int size = 0;

	public ConcreteIterator(ConcreteTeacher concreteTeacher)
	{
		this.concreteTeacher = concreteTeacher;
		size = concreteTeacher.getSize();
		index = 0;
	}

	@Override
	public void first()
	{
		index = 0;
	}

	@Override
	public void next()
	{
		if ( index <= size )
		{
			index++;
		}
	}

	@Override
	public boolean isDone()
	{
		return index >= size;
	}

	@Override
	public String currentItem()
	{
		return concreteTeacher.getElement(index);
	}
}
